<template>
  <el-card class="box-card">
    <div
      slot="header"
      class="clearfix"
    >
      <span>个人信息</span>
    </div>
    <div class="info-item">
      <el-avatar
        :size="100"
        src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
      ></el-avatar>
    </div>
    <div class="info-item">
      <el-descriptions
        :column="1"
        border
      >
        <el-descriptions-item label="用户名">{{ userInfo.nickName }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ userInfo.userPhoneNum }}</el-descriptions-item>
        <el-descriptions-item label="登录密码"><el-link type="primary" @click="editPwd">去设置</el-link></el-descriptions-item>
        <el-descriptions-item label="企业绑定">
          <div v-if="userInfo.companyId">{{ userInfo.companyName }}</div>
          <el-link
            v-else
            type="primary"
            @click="onCompany"
          >去绑定</el-link>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <el-dialog
      title="企业绑定"
      :visible.sync="dialogVisible"
      width="1000px"
    >
      <div>
        <el-form
          ref="companyForm"
          :model="companyForm"
          :rules="rules"
          label-width="180px"
          style="max-width: 800px; margin: 0 auto;"
        >
          <el-form-item
            label="企业名称"
            prop="companyName"
          >
            <el-input
              v-model="companyForm.companyName"
              placeholder="请输入企业名称"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="统一社会信用代码"
            prop="creditCode"
          >
            <el-input
              v-model="companyForm.creditCode"
              placeholder="请输入统一社会信用代码"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="法定代表人姓名"
            prop="legalName"
          >
            <el-input
              v-model="companyForm.legalName"
              placeholder="请输入法定代表人姓名"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="法人证件类型"
            prop="legalIdType"
          >
            <el-select
              v-model="companyForm.legalIdType"
              placeholder="请选择法人证件类型"
            >
              <el-option
                label="大陆居民二代身份证"
                :value="0"
              ></el-option>
              <el-option
                label="港澳台居民来往内地通行证"
                :value="1"
              ></el-option>
              <el-option
                label="外国人永久居留证"
                :value="2"
              ></el-option>
              <el-option
                label="定居国外的中国公民护照"
                :value="3"
              ></el-option>
              <el-option
                label="港澳台居民居住证"
                :value="4"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="法定代表人证件号码"
            prop="legalIdCard"
          >
            <el-input
              v-model="companyForm.legalIdCard"
              placeholder="请输入法定代表人证件号码"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="短信验证码"
            prop="smsCode"
          >
            <div style="display: flex; width: 100%;">
              <el-input
                v-model="companyForm.smsCode"
                placeholder="请输入短信验证码"
                style="flex: 1;"
              ></el-input>
              <el-button
                type="primary"
                style="margin-left: 10px;"
                :disabled="smsCodeDisabled"
                @click="sendCode"
              >
                {{ smsCodeText }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="修改密码" width="530px" :visible.sync="showPwdDialog" custom-class="my-dialog" :close-on-click-modal="false">
      <el-form :model="pwdForm" :rules="pwdRules" ref="pwdFormRef" style="margin-top: -20px;" label-width="100px"
        size="medium" label-suffix=":">
        <el-form-item label="">
           <span>当前绑定手机号:{{userInfo.userPhoneNum}}</span>
        </el-form-item>
        <el-form-item prop="code">
            <el-input v-model="pwdForm.code" placeholder="请输入图形验证码">
              <template #append>
                <img @click="getImgCaptcha" style="cursor: pointer;height:34px" :src="captchaObj?.img"  />
              </template>
            </el-input>
        </el-form-item>
        <el-form-item placeholder="请输入手机验证码" prop="smsCode">
            <el-input v-model="pwdForm.smsCode" placeholder="请输入手机验证码" autocomplete="off">
              <template #append>
                <el-button :disabled="countdown > 0" @click="getPwdSmsCode" >{{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}</el-button>
              </template>
            </el-input>
        </el-form-item>
        <el-form-item label="">
           <span class="text-sm text-[#F56C6C]">*请设置包含字母、符号或数字中至少两项,长度超过6位的密码</span>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="pwdForm.newPassword" placeholder="请输入新密码" show-password autocomplete="new-password" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="pwdForm.confirmPassword" placeholder="请再次输入新密码" show-password autocomplete="new-password" />
        </el-form-item>
      </el-form>
      <div slot="footer" style="margin-top: -30px;text-align: center;">
        <el-button :loading="confirmLoading" type="primary" @click="editPwdSubmit">保存</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { mapGetters } from "vuex";
import { sendSmsCode, authCompany,changePassword,sendChangePasswordSmsCode,getcode, } from "@/api/user";
export default {
  name: "PersonalCenter",
  data() {
    var validatePassword = (rule, value, callback) => {
        var reg = /^\S*(?=\S{8})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*?.])\S*$/;
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (!reg.test(value)) {
          callback(new Error('密码长度8-20位，至少包含1个大写字母，1个小写字母，1个数字和一个特殊符号(!@#$%^&*?.)'));
        } else {
          callback();
        }
    };
    var validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.pwdForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      smsCodeDisabled: false,
      smsCodeText: "获取验证码",
      companyForm: {
        companyName: "",
        creditCode: "",
        legalName: "",
        legalIdType: 0,
        legalIdCard: "",
        smsCode: "",
      },
      rules: {
        companyName: [
          { required: true, message: "请输入企业名称", trigger: "blur" },
        ],
        creditCode: [
          {
            required: true,
            message: "请输入统一社会信用代码",
            trigger: "blur",
          },
        ],
        legalName: [
          { required: true, message: "请输入法定代表人姓名", trigger: "blur" },
        ],
        legalIdType: [
          {
            required: true,
            message: "请选择正确的身份证件类型",
            trigger: "change",
          },
        ],
        legalIdCard: [
          {
            required: true,
            message: "请输入法定代表人证件号码",
            trigger: "blur",
          },
        ],
        smsCode: [
          { required: true, message: "请输入短信验证码", trigger: "blur" },
          {
            pattern: /^\d{6}$/,
            message: "请输入6位数字短信验证码",
            trigger: "blur",
          },
        ],
      },
      showPwdDialog:false,
        pwdForm: {
        code: '',
        smsCode: '',
        newPassword: '',
        newPasswordConfirm: ''
      },
      pwdRules: {
        code: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }],
        smsCode: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }],
        newPassword: [{ required: true, validator: validatePassword, trigger: 'blur' }],
        confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: 'blur' }]
      },
      confirmLoading: false,
      step: 0,
      captchaObj: {
        img: '',
        uuid: ''
      },
      phoneCaptchaObj: {
        img: '',
        uuid: ''
      },
      countdown: 0
    };
  },
  computed: {
    ...mapGetters("user", ["userInfo"]),
  },
  methods: {
    editPwd() {
      this.showPwdDialog = true
       this.step = 0;
      this.getImgCaptcha()
    },
    onCompany() {
      this.dialogVisible = true;
    },
    // 获得默认账号密码登录的图形验证码
    getImgCaptcha() {
      getcode().then(res => {
        this.captchaObj.img = 'data:image/png;base64,' + res.img;
        this.captchaObj.uuid = res.uuid;
      });
    },
    // 设置密码时发送图形验证码
    getPwdSmsCode() {
      sendChangePasswordSmsCode().then(res => {
        if (res.code === 200) {
          this.$message.success('验证码发送成功！');
          this.countdown = 60;
          const timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        }else{
          this.getImgCaptcha();
        }
      }).finally(() => {
      });
    },
    editPwdSubmit() {
      this.$refs.pwdFormRef.validate((valid) => {
        if (valid) {
          this.pwdForm.uuid = this.captchaObj.uuid
          this.confirmLoading = true
          changePassword(this.pwdForm).then(res => {
            // this.$message.success('修改密码成功')
            if (res.code === 200) {
              this.$message.success('修改密码成功')
              this.showPwdDialog = false
            }else{
              this.getImgCaptcha()
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        } else {
          return false
        }
      })
    },
    sendCode() {
      // 这里实现发送短信验证码的逻辑
      this.smsCodeDisabled = true;
      let count = 60;
      this.smsCodeText = `${count}秒后重新获取`;

      sendSmsCode({ mobile: this.userInfo.userPhoneNum, scene: 6 }).then(
        (res) => {
          if (res.code === 200) {
            this.$message.success("验证码发送成功！");
            this.showDialog = false;
            this.countdown = 60;
            const timer = setInterval(() => {
              this.countdown--;
              if (this.countdown <= 0) {
                clearInterval(timer);
              }
            }, 1000);
          }
        }
      );
    },
    submitForm() {
      this.$refs.companyForm.validate((valid) => {
        if (valid) {
          authCompany(this.companyForm).then((res) => {
            this.$message.success("企业绑定成功");
            this.$store.dispatch("user/getUserInfo")
            this.dialogVisible = false;
          });
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
  },
  mounted() {
    
  },
};
</script>

<style scoped>
.info-item {
  margin-bottom: 20px;
  text-align: center;
}

.box-card {
  height: 100%;
}
</style>